"""
微密圈下载页面 - GUI界面
"""

import os
import json
import re
import time
import gc
from concurrent.futures import ThreadPoolExecutor, as_completed

# 尝试导入psutil，如果没有安装则使用简化版本
try:
    import psutil

    PSUTIL_AVAILABLE = True
except ImportError:
    PSUTIL_AVAILABLE = False
from PySide2.QtWidgets import (
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QFileDialog,
    QProgressBar,
    QTextEdit,
    QFrame,
    QGroupBox,
    QSpinBox,
    QCheckBox,
    QMessageBox,
    QTabWidget,
    QPlainTextEdit,
    QDialog,
    QDialogButtonBox,
    QStackedWidget,
    QComboBox,
    QScrollArea,
)
from PySide2.QtCore import Qt, QTimer, QThread, Signal, QPropertyAnimation, QEasingCurve
from PySide2.QtGui import (
    QFont,
    QPixmap,
    QPainter,
    QBrush,
    QColor,
    QLinearGradient,
    QRadialGradient,
)

from ui_components import DownloadPageComponent
from vmq_downloader import WeimiquanDownloader, WeimiquanDownloadThread
from vmq_batch import batch_crawl_vmq, get_vmq_data, extract_posts_from_response
from tiefenquan_downloader import (
    TiefenquanDownloader,
    TiefenquanDownloadThread,
    TiefenquanVideoDownloader,
    TiefenquanVideoDownloadThread,
)
from config import APP_CONFIG
from custom_message_box import warning, critical, question


class WeimiquanPage(DownloadPageComponent):
    """微密圈下载页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.downloader = WeimiquanDownloader()
        self.tiefenquan_downloader = TiefenquanDownloader()
        self.tiefenquan_video_downloader = TiefenquanVideoDownloader()
        self.download_thread = None
        self.batch_thread = None
        self.tiefenquan_thread = None
        self.tiefenquan_video_thread = None
        self.is_downloading = False
        self.is_batch_downloading = False
        self.is_tiefenquan_downloading = False
        self.is_tiefenquan_video_downloading = False
        self.current_mode = (
            "single"  # "single", "batch", "tiefenquan", 或 "tiefenquan_video"
        )
        self.setup_ui()
        self.ensure_download_directory()
        # 延迟连接信号，确保所有方法都已定义
        QTimer.singleShot(0, self.connect_signals)

    def setup_ui(self):
        """设置UI - 完全按照抖音、快手的样式"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # 标题区域 - 添加切换按钮
        title_frame = QFrame()
        title_frame.setStyleSheet(
            """
            QFrame {
                background: rgba(255, 255, 255, 0.08);
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
        """
        )
        title_frame.setFixedHeight(60)
        title_layout = QHBoxLayout(title_frame)
        title_layout.setContentsMargins(15, 5, 15, 5)

        # 左侧装饰
        left_decor = QFrame()
        left_decor.setFixedWidth(4)
        left_decor.setStyleSheet("background-color: #ff6b9d; border-radius: 2px;")

        # 切换按钮
        from ui_styles import UIStyles

        self.ui_styles = UIStyles()

        self.single_mode_btn = QPushButton("付费区图片下载")
        self.single_mode_btn.setMinimumHeight(40)
        self.single_mode_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
        self.single_mode_btn.clicked.connect(lambda: self.switch_mode("single"))

        self.batch_mode_btn = QPushButton("付费区批量下载")
        self.batch_mode_btn.setMinimumHeight(40)
        self.batch_mode_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.batch_mode_btn.clicked.connect(lambda: self.switch_mode("batch"))

        self.tiefenquan_mode_btn = QPushButton("铁粉圈下载")
        self.tiefenquan_mode_btn.setMinimumHeight(40)
        self.tiefenquan_mode_btn.setStyleSheet(
            self.ui_styles.get_button_style("default")
        )
        self.tiefenquan_mode_btn.clicked.connect(lambda: self.switch_mode("tiefenquan"))

        self.tiefenquan_video_mode_btn = QPushButton("铁粉圈视频")
        self.tiefenquan_video_mode_btn.setMinimumHeight(40)
        self.tiefenquan_video_mode_btn.setStyleSheet(
            self.ui_styles.get_button_style("default")
        )
        self.tiefenquan_video_mode_btn.clicked.connect(
            lambda: self.switch_mode("tiefenquan_video")
        )

        title_layout.addWidget(left_decor)
        title_layout.addWidget(self.single_mode_btn)
        title_layout.addWidget(self.batch_mode_btn)
        title_layout.addWidget(self.tiefenquan_mode_btn)
        title_layout.addWidget(self.tiefenquan_video_mode_btn)
        title_layout.addStretch()

        layout.addWidget(title_frame)

        # 创建堆叠布局用于切换页面
        self.stacked_widget = QStackedWidget()
        layout.addWidget(self.stacked_widget)

        # 创建单个下载页面
        self.setup_single_download_page()

        # 创建批量下载页面
        self.setup_batch_download_page()

        # 创建铁粉圈下载页面
        self.setup_tiefenquan_download_page()

        # 创建铁粉圈视频下载页面
        self.setup_tiefenquan_video_download_page()

    def setup_single_download_page(self):
        """设置单个下载页面"""
        single_page = QWidget()

        # 创建主布局
        main_layout = QVBoxLayout(single_page)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setStyleSheet(
            """
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """
        )

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet(
            """
            QWidget {
                background: transparent;
            }
        """
        )

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # URL输入区域 - 完全按照原版
        url_group = QGroupBox("图片链接")
        url_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        url_layout = QVBoxLayout(url_group)
        url_layout.setContentsMargins(12, 15, 12, 12)

        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText(
            "http://wmqxz.net/archives/1955570181625102336"
        )
        self.url_input.setMinimumHeight(42)
        self.url_input.setStyleSheet(
            """
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) ;
                border: 2px solid rgba(255, 255, 255, 0.15) ;
                border-radius: 12px ;
                color: #ffffff;
                padding: 12px 16px ;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """
        )

        url_layout.addWidget(self.url_input)
        layout.addWidget(url_group)

        # 保存路径区域 - 完全按照原版
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("保存到:")
        path_label.setStyleSheet("color: #ffffff; margin-right: 10px;")

        self.path_input = QLineEdit()
        self.path_input.setText(APP_CONFIG["download_paths"]["weimiquan_image"])
        self.path_input.setMinimumHeight(42)
        self.path_input.setStyleSheet(
            """
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """
        )

        self.browse_btn = QPushButton("浏览")
        self.browse_btn.setMinimumHeight(42)
        self.browse_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.browse_btn.clicked.connect(self.browse_folder)

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_input, 1)
        path_layout.addWidget(self.browse_btn)
        layout.addWidget(path_group)

        # 操作按钮区域 - 按照快手页面样式
        button_group = QGroupBox("操作")
        button_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        self.download_btn = QPushButton("开始下载")
        self.download_btn.setMinimumHeight(42)
        self.download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
        self.download_btn.clicked.connect(self.start_download)

        self.clear_btn = QPushButton("清空日志")
        self.clear_btn.setMinimumHeight(42)
        self.clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.clear_btn.clicked.connect(self.clear_log)

        button_layout.addWidget(self.download_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()
        layout.addWidget(button_group)

        # 下载进度区域 - 完全按照快手页面样式
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimumHeight(30)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet(
            """
           QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """
        )
        progress_layout.addWidget(self.progress_bar)
        layout.addWidget(progress_group)

        # 日志区域 - 完全按照原版
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.log_text = QTextEdit()
        self.log_text.setMinimumHeight(300)  # 设置合适的高度
        self.log_text.setMaximumHeight(300)  # 限制最大高度
        self.log_text.setReadOnly(True)
        self.log_text.setStyleSheet(
            """
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 8px;
                color: #ffffff;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                padding: 8px;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.05);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:0.5 #667eea, stop:1 #764ba2);
                border-radius: 6px;
                min-height: 20px;
                margin: 2px;
            }
            QScrollBar::handle:vertical:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00e5ff, stop:0.5 #7c8cff, stop:1 #8a5cb8);
                box-shadow: 0 0 8px rgba(0, 212, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
                height: 0px;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                background: none;
            }
        """
        )

        log_layout.addWidget(self.log_text)
        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)

        # 添加到堆叠布局
        self.stacked_widget.addWidget(single_page)

    def setup_batch_download_page(self):
        """设置批量下载页面"""
        batch_page = QWidget()
        batch_page.setStyleSheet(
            """
            QWidget {
                background: transparent;
            }
        """
        )

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setStyleSheet(
            """
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """
        )

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet(
            """
            QWidget {
                background: transparent;
            }
        """
        )
        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        # 批量下载配置区域
        config_group = QGroupBox("批量下载配置")
        config_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        config_layout = QVBoxLayout(config_group)
        config_layout.setContentsMargins(12, 15, 12, 12)
        config_layout.setSpacing(15)

        # 分类和页数输入 - 使用网格布局
        inputs_layout = QVBoxLayout()
        inputs_layout.setSpacing(12)

        # 分类输入
        category_row = QHBoxLayout()
        category_label = QLabel("分类:")
        category_label.setStyleSheet(
            "color: #ffffff; font-size: 11pt; font-weight: normal;"
        )
        category_label.setFixedWidth(50)

        self.category_input = QLineEdit()
        self.category_input.setPlaceholderText("mote")
        self.category_input.setText("mote")
        self.category_input.setMinimumHeight(42)
        self.category_input.setStyleSheet(
            """
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """
        )

        category_row.addWidget(category_label)
        category_row.addWidget(self.category_input)
        inputs_layout.addLayout(category_row)

        # 页数输入
        page_row = QHBoxLayout()
        page_label = QLabel("页数:")
        page_label.setStyleSheet(
            "color: #ffffff; font-size: 11pt; font-weight: normal;"
        )
        page_label.setFixedWidth(50)

        self.page_input = QLineEdit()
        self.page_input.setPlaceholderText("1")
        self.page_input.setText("1")
        self.page_input.setMinimumHeight(42)
        self.page_input.setStyleSheet(
            """
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """
        )

        page_row.addWidget(page_label)
        page_row.addWidget(self.page_input)
        inputs_layout.addLayout(page_row)

        config_layout.addLayout(inputs_layout)
        layout.addWidget(config_group)

        # 保存路径区域
        batch_path_group = QGroupBox("保存路径")
        batch_path_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        batch_path_layout = QHBoxLayout(batch_path_group)
        batch_path_layout.setContentsMargins(12, 15, 12, 12)

        batch_path_label = QLabel("保存到:")
        batch_path_label.setStyleSheet(
            "color: #ffffff; font-size: 11pt; font-weight: normal;"
        )

        # 自动设置为 D:\douyin_downloads\wm-batch 文件夹
        batch_path = r"D:\douyin_downloads\wm-batch"

        self.batch_path_input = QLineEdit()
        self.batch_path_input.setText(batch_path)
        self.batch_path_input.setReadOnly(True)  # 设为只读，不允许修改
        self.batch_path_input.setMinimumHeight(42)
        self.batch_path_input.setStyleSheet(
            """
            QLineEdit {
                background: rgba(255, 255, 255, 0.05) !important;
                border: 2px solid rgba(255, 255, 255, 0.1) !important;
                border-radius: 12px !important;
                color: #cccccc !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
        """
        )

        batch_path_layout.addWidget(batch_path_label)
        batch_path_layout.addWidget(self.batch_path_input, 1)
        layout.addWidget(batch_path_group)

        # 批量操作按钮
        batch_button_group = QGroupBox("操作")
        batch_button_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        batch_button_layout = QHBoxLayout(batch_button_group)
        batch_button_layout.setContentsMargins(12, 15, 12, 12)

        self.batch_download_btn = QPushButton("开始批量下载")
        self.batch_download_btn.setMinimumHeight(42)
        self.batch_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )
        self.batch_download_btn.clicked.connect(self.start_batch_download)

        self.batch_clear_btn = QPushButton("清空日志")
        self.batch_clear_btn.setMinimumHeight(42)
        self.batch_clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.batch_clear_btn.clicked.connect(self.clear_batch_log)

        batch_button_layout.addWidget(self.batch_download_btn)
        batch_button_layout.addWidget(self.batch_clear_btn)
        batch_button_layout.addStretch()
        layout.addWidget(batch_button_group)

        # 批量下载进度
        batch_progress_group = QGroupBox("下载进度")
        batch_progress_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        batch_progress_layout = QVBoxLayout(batch_progress_group)
        batch_progress_layout.setContentsMargins(12, 15, 12, 12)

        self.batch_progress_bar = QProgressBar()
        self.batch_progress_bar.setMinimumHeight(30)
        self.batch_progress_bar.setValue(0)
        self.batch_progress_bar.setStyleSheet(
            """
           QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """
        )
        batch_progress_layout.addWidget(self.batch_progress_bar)
        layout.addWidget(batch_progress_group)

        # 批量下载日志
        batch_log_group = QGroupBox("下载日志")
        batch_log_group.setMinimumHeight(
            580
        )  # 设置最小高度确保日志框有足够空间（减少到580px）
        batch_log_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        batch_log_layout = QVBoxLayout(batch_log_group)
        batch_log_layout.setContentsMargins(12, 15, 12, 12)

        self.batch_log_text = QTextEdit()
        self.batch_log_text.setMinimumHeight(540)
        self.batch_log_text.setMaximumHeight(540)  # 设置最大高度而不是固定高度
        self.batch_log_text.setReadOnly(True)
        self.batch_log_text.setStyleSheet(
            """
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                padding: 12px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                line-height: 1.4;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.05);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:0.5 #667eea, stop:1 #764ba2);
                border-radius: 6px;
                min-height: 20px;
                margin: 2px;
            }
            QScrollBar::handle:vertical:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00e5ff, stop:0.5 #7c8cff, stop:1 #8a5cb8);
                box-shadow: 0 0 8px rgba(0, 212, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
                height: 0px;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                background: none;
            }
        """
        )

        batch_log_layout.addWidget(self.batch_log_text)
        layout.addWidget(batch_log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)

        # 批量下载页面的主布局
        main_layout = QVBoxLayout(batch_page)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.addWidget(scroll_area)

        # 添加到堆叠布局
        self.stacked_widget.addWidget(batch_page)

    def switch_mode(self, mode):
        """切换模式"""
        self.current_mode = mode
        if mode == "single":
            self.stacked_widget.setCurrentIndex(0)
            self.single_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("primary")
            )
            self.batch_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.tiefenquan_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.tiefenquan_video_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
        elif mode == "batch":
            self.stacked_widget.setCurrentIndex(1)
            self.single_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.batch_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("primary")
            )
            self.tiefenquan_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.tiefenquan_video_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
        elif mode == "tiefenquan":
            self.stacked_widget.setCurrentIndex(2)
            self.single_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.batch_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.tiefenquan_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("primary")
            )
            self.tiefenquan_video_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
        elif mode == "tiefenquan_video":
            self.stacked_widget.setCurrentIndex(3)
            self.single_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.batch_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.tiefenquan_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("default")
            )
            self.tiefenquan_video_mode_btn.setStyleSheet(
                self.ui_styles.get_button_style("primary")
            )

    def setup_tiefenquan_download_page(self):
        """设置铁粉圈下载页面"""
        tiefenquan_page = QWidget()

        # 创建主布局
        main_layout = QVBoxLayout(tiefenquan_page)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setStyleSheet(
            """
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """
        )

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet(
            """
            QWidget {
                background: transparent;
            }
        """
        )

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # URL输入区域
        url_group = QGroupBox("铁粉圈网页链接")
        url_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        url_layout = QVBoxLayout(url_group)
        url_layout.setContentsMargins(12, 15, 12, 12)

        self.tiefenquan_url_input = QLineEdit()
        self.tiefenquan_url_input.setPlaceholderText(
            "https://www.tiefenquan1.com/tiefenkongjian/post/4330.html"
        )
        self.tiefenquan_url_input.setMinimumHeight(42)
        self.tiefenquan_url_input.setStyleSheet(
            """ 
        QLineEdit {
                                                background:rgba(255, 255, 255, 0.08) ;
                                                border: 2px solid rgba(255, 255, 255, 0.15) ;
                                                border-radius: 12px ;
                                                color: #ffffff ;
                                                padding: 12px 16px ;
                                                font-size: 10pt;
                                            }
                                                QLineEdit:focus {
                                                background: rgba(255, 255, 255, 0.12) !important;
                                                border: 2px solid rgba(0, 212, 255, 0.5) !important;
                                            }

"""
        )
        url_layout.addWidget(self.tiefenquan_url_input)
        layout.addWidget(url_group)

        # 保存路径区域
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("保存路径:")
        path_label.setFont(QFont("Microsoft YaHei UI", 9, QFont.Medium))
        path_label.setStyleSheet("color: #ffffff; margin-right: 10px;")

        self.tiefenquan_path_input = QLineEdit()
        self.tiefenquan_path_input.setPlaceholderText("选择图片保存路径...")
        self.tiefenquan_path_input.setText(
            APP_CONFIG["download_paths"]["tiefenquan_image"]
        )
        self.tiefenquan_path_input.setMinimumHeight(42)

        self.tiefenquan_browse_btn = QPushButton("浏览")
        self.tiefenquan_browse_btn.setMinimumHeight(42)
        self.tiefenquan_browse_btn.setStyleSheet(
            self.ui_styles.get_button_style("default")
        )
        # 确保按钮可用
        self.tiefenquan_browse_btn.setEnabled(True)
        self.tiefenquan_browse_btn.setFocusPolicy(Qt.StrongFocus)
        print("🔧 铁粉圈浏览按钮已创建并设置为可用状态")

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.tiefenquan_path_input, 1)
        path_layout.addWidget(self.tiefenquan_browse_btn)

        layout.addWidget(path_group)

        # 操作按钮区域
        button_group = QGroupBox("操作")
        button_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        self.tiefenquan_download_btn = QPushButton("开始下载")
        self.tiefenquan_download_btn.setMinimumHeight(42)
        self.tiefenquan_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )

        self.tiefenquan_clear_btn = QPushButton("清空日志")
        self.tiefenquan_clear_btn.setMinimumHeight(42)
        self.tiefenquan_clear_btn.setStyleSheet(
            self.ui_styles.get_button_style("default")
        )

        button_layout.addWidget(self.tiefenquan_download_btn)
        button_layout.addWidget(self.tiefenquan_clear_btn)
        button_layout.addStretch()

        layout.addWidget(button_group)

        # 下载进度区域
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)

        self.tiefenquan_progress_bar = QProgressBar()
        self.tiefenquan_progress_bar.setMinimumHeight(30)
        self.tiefenquan_progress_bar.setValue(0)
        self.tiefenquan_progress_bar.setMaximum(100)
        self.tiefenquan_progress_bar.setStyleSheet(
            """
            QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """
        )

        progress_layout.addWidget(self.tiefenquan_progress_bar)

        layout.addWidget(progress_group)

        # 下载日志区域
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.tiefenquan_log_text = QTextEdit()
        self.tiefenquan_log_text.setReadOnly(True)
        self.tiefenquan_log_text.setMinimumHeight(300)
        self.tiefenquan_log_text.setMaximumHeight(300)
        self.tiefenquan_log_text.setStyleSheet(
            """
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                border: 1px solid rgba(255, 255, 255, 0.15);
                border-radius: 8px;
                color: #ffffff;
                font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
                font-size: 9pt;
                padding: 8px;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.05);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 #00d4ff, stop:0.5 #667eea, stop:1 #764ba2);
                border-radius: 6px;
                min-height: 20px;
                 margin: 2px;
            }
            QScrollBar::handle:vertical:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
            stop:0 #00e5ff, stop:0.5 #7c8cff, stop:1 #8a5cb8);
                box-shadow: 0 0 8px rgba(0, 212, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
                 height: 0px;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
          background: none;
}
        """
        )

        log_layout.addWidget(self.tiefenquan_log_text)

        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)

        # 添加到堆叠布局
        self.stacked_widget.addWidget(tiefenquan_page)

    def setup_tiefenquan_video_download_page(self):
        """设置铁粉圈视频下载页面"""
        tiefenquan_video_page = QWidget()

        # 创建主布局
        main_layout = QVBoxLayout(tiefenquan_video_page)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setStyleSheet(
            """
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """
        )

        scroll_content = QWidget()
        scroll_content.setStyleSheet(
            """
            QWidget {
                background: transparent;
            }

"""
        )

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # URL输入区域
        url_group = QGroupBox("铁粉圈视频链接")
        url_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        url_layout = QVBoxLayout(url_group)
        url_layout.setContentsMargins(12, 15, 12, 12)

        # URL输入框
        self.tiefenquan_video_url_input = QLineEdit()
        self.tiefenquan_video_url_input.setPlaceholderText(
            "https://www.tiefenquan1.com/tiefenkongjian/post/2987.html"
        )
        self.tiefenquan_video_url_input.setMinimumHeight(42)
        self.tiefenquan_video_url_input.setStyleSheet(
            """
            QLineEdit {
                background: rgba(255, 255, 255, 0.08);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                background: rgba(255, 255, 255, 0.1);
                color: #ffffff;
                padding: 12px 16px;
                font-size: 10pt;
            }
            QLineEdit:focus {
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
                background: rgba(255, 255, 255, 0.12) !important;
            }
        """
        )

        url_layout.addWidget(self.tiefenquan_video_url_input)
        layout.addWidget(url_group)

        # 保存路径区域
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("保存路径:")
        path_label.setStyleSheet("color: #ffffff; margin-right: 10px;")

        self.tiefenquan_video_path_input = QLineEdit()
        self.tiefenquan_video_path_input.setPlaceholderText("选择视频保存路径...")
        self.tiefenquan_video_path_input.setText(
            APP_CONFIG["download_paths"]["tiefenquan_video"]
        )
        self.tiefenquan_video_path_input.setMinimumHeight(42)
        self.path_input.setStyleSheet(
            """
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """
        )
        self.tiefenquan_video_browse_btn = QPushButton("浏览")
        self.tiefenquan_video_browse_btn.setMinimumHeight(42)
        self.tiefenquan_video_browse_btn.setStyleSheet(
            self.ui_styles.get_button_style("default")
        )

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.tiefenquan_video_path_input, 1)
        path_layout.addWidget(self.tiefenquan_video_browse_btn)

        layout.addWidget(path_group)

        # 操作按钮区域
        button_group = QGroupBox("操作")
        button_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                     stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                     color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        self.tiefenquan_video_download_btn = QPushButton("开始下载")
        self.tiefenquan_video_download_btn.setMinimumHeight(42)
        self.tiefenquan_video_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )
        print(f"🔘 铁粉圈视频下载按钮已创建: {self.tiefenquan_video_download_btn}")

        self.tiefenquan_video_clear_btn = QPushButton("清空日志")
        self.tiefenquan_video_clear_btn.setMinimumHeight(42)
        self.tiefenquan_video_clear_btn.setStyleSheet(
            self.ui_styles.get_button_style("default")
        )

        button_layout.addWidget(self.tiefenquan_video_download_btn)
        button_layout.addWidget(self.tiefenquan_video_clear_btn)
        button_layout.addStretch()
        layout.addWidget(button_group)

        # 下载进度区域
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                     stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)
        self.tiefenquan_video_progress_bar = QProgressBar()
        self.tiefenquan_video_progress_bar.setMinimumHeight(30)
        self.tiefenquan_video_progress_bar.setValue(0)
        self.tiefenquan_video_progress_bar.setStyleSheet(
            """
           QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """
        )

        progress_layout.addWidget(self.tiefenquan_video_progress_bar)
        layout.addWidget(progress_group)

        # 下载日志区域
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet(
            """
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;        
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                   stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """
        )
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.tiefenquan_video_log_text = QTextEdit()
        self.tiefenquan_video_log_text.setMinimumHeight(300)
        self.tiefenquan_video_log_text.setMaximumHeight(300)  # 限制最大高度
        self.tiefenquan_video_log_text.setReadOnly(True)
        self.tiefenquan_video_log_text.setStyleSheet(
            """
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 8px;
                color: #ffffff;
                font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
                font-size: 9pt;
                padding: 8px;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.05);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                    stop:0 #00d4ff, stop:0.5 #667eea, stop:1 #764ba2);
                                                     border-radius: 6px;
                                                     min-height: 20px;
                                                     margin: 2px;                    
                     } 
                     
                     
                     
                           
         QScrollBar::handle:vertical:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00e5ff, stop:0.5 #7c8cff, stop:1 #8a5cb8);
 box-shadow: 0 0 8px rgba(0, 212, 255, 0.5);

            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
                 height: 0px;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
   }
        """
        )

        log_layout.addWidget(self.tiefenquan_video_log_text)
        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)

        # 添加到堆叠布局
        self.stacked_widget.addWidget(tiefenquan_video_page)

    def get_weimiquan_settings(self):
        """从设置页面获取微密圈配置"""
        try:
            settings_file = os.path.join(os.getcwd(), "weimiquan_settings.json")
            if os.path.exists(settings_file):
                with open(settings_file, "r", encoding="utf-8") as f:
                    return json.load(f)
        except Exception as e:
            print(f"加载微密圈设置失败: {e}")

        # 返回默认设置（包含默认Cookie）
        default_cookies = {
            "__51uvsct__KisFAjMmWonEmmaa": "1",
            "__51vcke__KisFAjMmWonEmmaa": "124af7b9-a489-54e1-9e9f-2aad28de65e5",
            "__51vuft__KisFAjMmWonEmmaa": "1747203033573",
            "__51uvsct__KpRFHkppObUqVbFN": "1",
            "__51vcke__KpRFHkppObUqVbFN": "af7f4762-a1c2-542c-b776-2e8c1f96f3bb",
            "__51vuft__KpRFHkppObUqVbFN": "1753076527969",
            "deviceId": "zREhXJja4epsynnSXydhrJ2M",
            "token": "45d27c4c99304d5fb41b2c2a63c4f350.2ROyMfQufDRX3KZY0rC5btihxlqNlZF585WuWf67FaUgWc%2BeEUUs%2FtUKd7XUku0FayrOvXG7gd4P2RGu7qZCqtXVFdAyJiqTHR1KGah%2FkYa6DccDX7eY1ddZ4bcWY6frF1T37kdU1bPq8YX5Jh3QLI0CDOgO1wRN.ab27735a0c4ae07381d4801495896644",
            "__vtins__KpRFHkppObUqVbFN": "%7B%22sid%22%3A%20%22a2055a9b-b372-522e-bd50-0495a37c8a44%22%2C%20%22vd%22%3A%2021%2C%20%22stt%22%3A%201331792%2C%20%22dr%22%3A%20274380%2C%20%22expires%22%3A%201753079659758%2C%20%22ct%22%3A%201753077859758%7D",
        }

        return {
            "proxy_host": "127.0.0.1",
            "proxy_port": 7890,
            "thread_count": 5,  # 固定为5个线程
            "cookies": default_cookies,
        }

    def connect_signals(self):
        """连接信号"""
        self.downloader.progress_updated.connect(self.update_progress_with_count)
        self.downloader.status_updated.connect(self.update_status)
        self.downloader.download_completed.connect(self.download_completed)
        self.downloader.error_occurred.connect(self.show_error)

        # 连接铁粉圈下载器信号
        self.tiefenquan_downloader.progress_updated.connect(
            self.update_tiefenquan_progress
        )
        self.tiefenquan_downloader.status_updated.connect(self.update_tiefenquan_status)
        self.tiefenquan_downloader.download_completed.connect(
            self.tiefenquan_download_completed
        )
        self.tiefenquan_downloader.error_occurred.connect(self.show_tiefenquan_error)
        self.tiefenquan_downloader.image_found.connect(self.tiefenquan_images_found)

        # 连接铁粉圈视频下载器信号
        try:
            print(f"🔗 连接铁粉圈视频下载器信号...")
            print(f"📋 下载器对象: {self.tiefenquan_video_downloader}")

            if hasattr(self.tiefenquan_video_downloader, "progress_updated"):
                self.tiefenquan_video_downloader.progress_updated.connect(
                    self.update_tiefenquan_video_progress
                )
                print("✅ progress_updated 信号连接成功")
            else:
                print("❌ tiefenquan_video_downloader 没有 progress_updated 信号")

            if hasattr(self.tiefenquan_video_downloader, "status_updated"):
                self.tiefenquan_video_downloader.status_updated.connect(
                    self.update_tiefenquan_video_status
                )
                print("✅ status_updated 信号连接成功")
            else:
                print("❌ tiefenquan_video_downloader 没有 status_updated 信号")

            if hasattr(self.tiefenquan_video_downloader, "download_completed"):
                self.tiefenquan_video_downloader.download_completed.connect(
                    self.tiefenquan_video_download_completed
                )
                print("✅ download_completed 信号连接成功")
            else:
                print("❌ tiefenquan_video_downloader 没有 download_completed 信号")

            if hasattr(self.tiefenquan_video_downloader, "error_occurred"):
                self.tiefenquan_video_downloader.error_occurred.connect(
                    self.show_tiefenquan_video_error
                )
                print("✅ error_occurred 信号连接成功")
            else:
                print("❌ tiefenquan_video_downloader 没有 error_occurred 信号")

        except Exception as e:
            print(f"❌ 铁粉圈视频下载器信号连接失败: {e}")
            import traceback

            traceback.print_exc()

        # 连接铁粉圈按钮信号 - 添加调试信息
        try:
            self.tiefenquan_browse_btn.clicked.connect(self.browse_tiefenquan_path)
            print("✅ 铁粉圈浏览按钮信号连接成功")
        except Exception as e:
            print(f"❌ 铁粉圈浏览按钮信号连接失败: {e}")
            # 备用方案：使用事件过滤器
            try:
                self.tiefenquan_browse_btn.installEventFilter(self)
                print("✅ 已安装事件过滤器作为备用方案")
            except Exception as e2:
                print(f"❌ 安装事件过滤器也失败: {e2}")

        try:
            self.tiefenquan_download_btn.clicked.connect(self.start_tiefenquan_download)
            print("✅ 铁粉圈下载按钮信号连接成功")
        except Exception as e:
            print(f"❌ 铁粉圈下载按钮信号连接失败: {e}")

        try:
            self.tiefenquan_clear_btn.clicked.connect(self.clear_tiefenquan_log)
            print("✅ 铁粉圈清空按钮信号连接成功")
        except Exception as e:
            print(f"❌ 铁粉圈清空按钮信号连接失败: {e}")

        # 连接铁粉圈视频按钮信号
        try:
            print(
                f"🔗 检查铁粉圈视频浏览按钮对象: {hasattr(self, 'tiefenquan_video_browse_btn')}"
            )
            if hasattr(self, "tiefenquan_video_browse_btn"):
                print(f"📋 浏览按钮对象: {self.tiefenquan_video_browse_btn}")
                print(f"📋 浏览方法对象: {self.browse_tiefenquan_video_path}")
                self.tiefenquan_video_browse_btn.clicked.connect(
                    self.browse_tiefenquan_video_path
                )
                print("✅ 铁粉圈视频浏览按钮信号连接成功")
            else:
                print("❌ 铁粉圈视频浏览按钮对象不存在")
        except Exception as e:
            print(f"❌ 铁粉圈视频浏览按钮信号连接失败: {e}")
            import traceback

            traceback.print_exc()

        try:
            print(
                f"🔗 检查铁粉圈视频下载按钮对象: {hasattr(self, 'tiefenquan_video_download_btn')}"
            )
            if hasattr(self, "tiefenquan_video_download_btn"):
                print(f"📋 下载按钮对象: {self.tiefenquan_video_download_btn}")
                print(f"📋 下载方法对象: {self.start_tiefenquan_video_download}")

                # 先断开所有现有连接
                try:
                    self.tiefenquan_video_download_btn.clicked.disconnect()
                    print("🔌 已断开现有连接")
                except:
                    print("🔌 没有现有连接需要断开")

                # 重新连接
                self.tiefenquan_video_download_btn.clicked.connect(
                    self.start_tiefenquan_video_download
                )
                print("✅ 铁粉圈视频下载按钮信号连接成功")

                # 测试按钮是否可点击
                print(
                    f"🔘 按钮是否启用: {self.tiefenquan_video_download_btn.isEnabled()}"
                )
                print(
                    f"🔘 按钮是否可见: {self.tiefenquan_video_download_btn.isVisible()}"
                )
            else:
                print("❌ 铁粉圈视频下载按钮对象不存在")
        except Exception as e:
            print(f"❌ 铁粉圈视频下载按钮信号连接失败: {e}")
            import traceback

            traceback.print_exc()

        try:
            self.tiefenquan_video_clear_btn.clicked.connect(
                self.clear_tiefenquan_video_log
            )
            print("✅ 铁粉圈视频清空按钮信号连接成功")
        except Exception as e:
            print(f"❌ 铁粉圈视频清空按钮信号连接失败: {e}")

    def browse_folder(self):
        """浏览文件夹"""
        folder = QFileDialog.getExistingDirectory(
            self, "选择保存路径", self.path_input.text()
        )
        if folder:
            self.path_input.setText(folder)

    def start_download(self):
        """开始/停止下载"""
        if self.is_downloading:
            # 停止下载
            self.stop_download()
        else:
            # 开始下载
            self.begin_download()

    def begin_download(self):
        """开始下载"""
        url = self.url_input.text().strip()
        if not url:
            warning(self, "警告", "请输入微密圈链接！")
            return

        if not (
            url.startswith("https://wmqxz.net/") or url.startswith("http://wmqxz.net/")
        ):
            warning(self, "警告", "请输入有效的微密圈链接！")
            return

        download_dir = self.path_input.text().strip()
        if not download_dir:
            warning(self, "警告", "请选择保存路径！")
            return

        # 获取微密圈设置
        settings = self.get_weimiquan_settings()

        # 检查Cookie配置（允许使用默认Cookie）
        cookies = settings.get("cookies")
        if not cookies:
            warning(self, "警告", "Cookie配置异常，请检查设置！")
            return

        # 重置UI状态
        self.is_downloading = True
        self.download_btn.setText("停止下载")
        self.progress_bar.setValue(0)
        self.log_text.clear()

        # 配置下载器
        self.downloader.set_proxy(settings["proxy_host"], settings["proxy_port"])
        self.downloader.set_cookies(settings["cookies"])
        self.downloader.set_thread_count(settings["thread_count"])

        # 开始下载
        self.download_thread = WeimiquanDownloadThread(
            self.downloader, url, download_dir
        )
        self.download_thread.start()

        self.append_log(f"开始下载: {url}")

    def stop_download(self):
        """停止下载"""
        if self.downloader:
            self.downloader.stop_download()

        if self.download_thread and self.download_thread.isRunning():
            self.download_thread.terminate()
            self.download_thread.wait()

        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.append_log("下载已停止")

    def update_progress_with_count(self, current, total):
        """更新进度条（带计数）"""
        if total > 0:
            progress = int((current / total) * 100)
            self.progress_bar.setValue(progress)
            self.append_log(f"下载进度: {current}/{total} ({progress}%)")

    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)

    def update_status(self, status):
        """更新状态"""
        self.append_log(status)

    def download_completed(self, success_count, failed_count, total_size_mb):
        """下载完成"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.progress_bar.setValue(100)
        self.append_log(
            f"下载完成! 成功: {success_count}, 失败: {failed_count}, 总大小: {total_size_mb:.2f}MB"
        )

    def download_finished(self):
        """下载完成（兼容方法）"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.progress_bar.setValue(100)
        self.append_log("下载完成!")

    def show_error(self, error_msg):
        """显示错误"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.append_log(f"错误: {error_msg}")
        # 使用自定义消息框
        from main_window import show_custom_message

        show_custom_message(self, "错误", f"下载失败: {error_msg}", "error")

    def clear_log(self):
        """清空日志"""
        self.log_text.clear()

    def ensure_download_directory(self):
        """确保下载目录存在"""
        # 使用config.py中定义的微密圈路径
        default_path = APP_CONFIG["download_paths"]["weimiquan_image"]
        if not os.path.exists(default_path):
            try:
                os.makedirs(default_path, exist_ok=True)
                print(f"[微密圈] 创建默认下载目录: {default_path}")
            except Exception as e:
                print(f"[微密圈] 创建目录失败: {str(e)}")
                default_path = os.path.expanduser("~/Downloads/wxPic")
                try:
                    os.makedirs(default_path, exist_ok=True)
                    print(f"[微密圈] 使用备用目录: {default_path}")
                except Exception as e2:
                    print(f"[微密圈] 创建备用目录也失败: {str(e2)}")
                    return

        # 设置默认路径
        if hasattr(self, "path_input") and not self.path_input.text().strip():
            self.path_input.setText(default_path)

        # 确保铁粉圈下载目录存在
        tiefenquan_path = APP_CONFIG["download_paths"]["tiefenquan_image"]
        if not os.path.exists(tiefenquan_path):
            try:
                os.makedirs(tiefenquan_path, exist_ok=True)
                print(f"[铁粉圈] 创建默认下载目录: {tiefenquan_path}")
            except Exception as e:
                print(f"[铁粉圈] 创建目录失败: {str(e)}")
                tiefenquan_path = os.path.expanduser("~/Downloads/tiefenquan")
                try:
                    os.makedirs(tiefenquan_path, exist_ok=True)
                    print(f"[铁粉圈] 使用备用目录: {tiefenquan_path}")
                except Exception as e2:
                    print(f"[铁粉圈] 创建备用目录也失败: {str(e2)}")
                    return

        # 设置铁粉圈默认路径
        if (
            hasattr(self, "tiefenquan_path_input")
            and not self.tiefenquan_path_input.text().strip()
        ):
            self.tiefenquan_path_input.setText(tiefenquan_path)

    def append_log(self, message):
        """添加日志"""
        from datetime import datetime

        timestamp = datetime.now().strftime("%H:%M:%S")
        self.log_text.append(f"[{timestamp}] {message}")
        self.log_text.ensureCursorVisible()

    def append_batch_log(self, message):
        """添加批量下载日志"""
        from datetime import datetime

        timestamp = datetime.now().strftime("%H:%M:%S")
        self.batch_log_text.append(f"[{timestamp}] {message}")
        self.batch_log_text.ensureCursorVisible()

    def clear_batch_log(self):
        """清空批量下载日志"""
        self.batch_log_text.clear()

    def start_batch_download(self):
        """开始批量下载"""
        if self.is_batch_downloading:
            self.stop_batch_download()
            return

        # 获取配置
        category = self.category_input.text().strip()
        page = self.page_input.text().strip()
        download_dir = self.batch_path_input.text().strip()

        if not category:
            warning(self, "警告", "请输入分类名称！")
            return

        if not page or not page.isdigit():
            warning(self, "警告", "请输入有效的页码！")
            return

        page_num = int(page)
        if page_num < 1:
            warning(self, "警告", "页码必须大于0！")
            return

        # 获取微密圈设置
        settings = self.get_weimiquan_settings()
        if not settings.get("cookies"):
            warning(self, "警告", "Cookie配置异常，请检查设置！")
            return

        self.append_batch_log(f"开始批量下载 - 分类: {category}, 页码: {page_num}")

        # 创建并启动批量下载线程（默认重试3次）
        self.batch_thread = BatchDownloadThread(
            category, page_num, download_dir, settings, max_retries=3
        )
        self.batch_thread.progress_updated.connect(self.update_batch_progress)
        self.batch_thread.status_updated.connect(self.append_batch_log)
        self.batch_thread.download_completed.connect(self.batch_download_completed)
        self.batch_thread.error_occurred.connect(self.show_batch_error)

        self.batch_thread.start()
        self.is_batch_downloading = True
        self.batch_download_btn.setText("停止下载")
        self.batch_download_btn.setStyleSheet(self.ui_styles.get_button_style("danger"))

    def stop_batch_download(self):
        """停止批量下载"""
        if self.batch_thread and self.batch_thread.isRunning():
            # 首先请求线程优雅停止
            self.batch_thread.request_stop()
            self.append_batch_log("正在停止批量下载...")

            # 等待线程自然结束，最多等待3秒
            if not self.batch_thread.wait(3000):  # 3秒超时
                self.append_batch_log("强制终止批量下载线程...")
                self.batch_thread.terminate()
                self.batch_thread.wait()

        self.is_batch_downloading = False
        self.batch_download_btn.setText("开始批量下载")
        self.batch_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )
        self.append_batch_log("批量下载已停止")

    def update_batch_progress(self, current, total):
        """更新批量下载进度"""
        if total > 0:
            progress = int((current / total) * 100)
            self.batch_progress_bar.setValue(progress)

    def batch_download_completed(self):
        """批量下载完成"""
        self.is_batch_downloading = False
        self.batch_download_btn.setText("开始批量下载")
        self.batch_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )
        self.batch_progress_bar.setValue(100)
        self.append_batch_log("✅ 批量下载完成！")
        # 移除弹框提示，只在日志中显示完成信息

    def show_batch_error(self, error_msg):
        """显示批量下载错误"""
        self.append_batch_log(f"❌ 错误: {error_msg}")
        # 使用自定义消息框
        from main_window import show_custom_message

        show_custom_message(self, "错误", f"批量下载出错：{error_msg}", "error")

    # ====== 铁粉圈相关方法 ======

    def browse_tiefenquan_path(self):
        """浏览铁粉圈保存路径"""
        try:
            print("🔍 铁粉圈浏览按钮被点击")
            current_path = self.tiefenquan_path_input.text()
            print(f"📁 当前路径: {current_path}")

            folder = QFileDialog.getExistingDirectory(
                self, "选择铁粉圈图片保存路径", current_path if current_path else ""
            )

            if folder:
                print(f"✅ 选择的路径: {folder}")
                self.tiefenquan_path_input.setText(folder)
                # 添加日志提示
                self.add_tiefenquan_log(f"📁 已选择保存路径: {folder}")
            else:
                print("❌ 用户取消了路径选择")

        except Exception as e:
            print(f"❌ 浏览路径时发生错误: {e}")
            # 显示错误消息
            critical(self, "错误", f"浏览路径时发生错误:\n{str(e)}")

    def start_tiefenquan_download(self):
        """开始/停止铁粉圈下载"""
        if self.is_tiefenquan_downloading:
            # 停止下载
            self.stop_tiefenquan_download()
        else:
            # 开始下载
            self.begin_tiefenquan_download()

    def begin_tiefenquan_download(self):
        """开始铁粉圈下载"""
        url = self.tiefenquan_url_input.text().strip()
        if not url:
            warning(self, "警告", "请输入铁粉圈网页链接！")
            return

        folder_path = self.tiefenquan_path_input.text().strip()
        if not folder_path:
            warning(self, "警告", "请选择保存路径！")
            return

        # 验证URL格式
        if not url.startswith(("http://", "https://")):
            warning(self, "警告", "请输入有效的网页链接！")
            return

        # 设置下载状态
        self.is_tiefenquan_downloading = True
        self.tiefenquan_download_btn.setText("停止下载")
        self.tiefenquan_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("danger")
        )
        self.tiefenquan_progress_bar.setValue(0)

        # 添加开始日志
        self.add_tiefenquan_log("🚀 开始铁粉圈图片下载...")
        self.add_tiefenquan_log(f"📎 链接: {url}")
        self.add_tiefenquan_log(f"📁 保存路径: {folder_path}")

        # 启动下载线程
        self.tiefenquan_thread = TiefenquanDownloadThread(
            self.tiefenquan_downloader, url, folder_path
        )
        self.tiefenquan_thread.start()

    def stop_tiefenquan_download(self):
        """停止铁粉圈下载"""
        if self.tiefenquan_thread and self.tiefenquan_thread.isRunning():
            self.tiefenquan_downloader.stop_download()
            self.tiefenquan_thread.quit()
            self.tiefenquan_thread.wait()

        self.is_tiefenquan_downloading = False
        self.tiefenquan_download_btn.setText("开始下载")
        self.tiefenquan_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )
        self.add_tiefenquan_log("⏹️ 下载已停止")

    def clear_tiefenquan_log(self):
        """清空铁粉圈日志"""
        self.tiefenquan_log_text.clear()
        self.add_tiefenquan_log("🧹 日志已清空")

    def add_tiefenquan_log(self, message):
        """添加铁粉圈日志"""
        import time

        timestamp = time.strftime("%H:%M:%S")
        log_entry = f"[{timestamp}] {message}"
        self.tiefenquan_log_text.append(log_entry)

        # 自动滚动到底部
        scrollbar = self.tiefenquan_log_text.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())

    # 铁粉圈下载器信号处理方法
    def update_tiefenquan_progress(self, progress):
        """更新铁粉圈下载进度"""
        self.tiefenquan_progress_bar.setValue(progress)

    def update_tiefenquan_status(self, message):
        """更新铁粉圈状态"""
        self.add_tiefenquan_log(message)

    def tiefenquan_download_completed(self, success, folder_path):
        """铁粉圈下载完成"""
        self.is_tiefenquan_downloading = False
        self.tiefenquan_download_btn.setText("开始下载")
        self.tiefenquan_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )

        if success:
            self.tiefenquan_progress_bar.setValue(100)
            self.add_tiefenquan_log("🎉 铁粉圈图片下载完成！")

            # 询问是否打开文件夹 - 使用自定义毛玻璃对话框
            reply = self.show_download_complete_dialog(folder_path)

            if reply:
                import subprocess
                import sys

                if sys.platform == "win32":
                    os.startfile(folder_path)
                elif sys.platform == "darwin":
                    subprocess.run(["open", folder_path])
                else:
                    subprocess.run(["xdg-open", folder_path])
        else:
            self.add_tiefenquan_log("❌ 铁粉圈下载失败")

    def show_tiefenquan_error(self, error_message):
        """显示铁粉圈错误"""
        self.add_tiefenquan_log(f"❌ 错误: {error_message}")
        critical(self, "铁粉圈下载错误", error_message)

    def tiefenquan_images_found(self, count):
        """发现铁粉圈图片"""
        self.add_tiefenquan_log(f"🔍 发现 {count} 张图片，准备下载...")

    def show_download_complete_dialog(self, folder_path):
        """显示自定义的下载完成对话框"""
        try:
            # 创建自定义对话框
            dialog = DownloadCompleteDialog(self, folder_path)
            result = dialog.exec_()
            return result == QDialog.Accepted
        except Exception as e:
            print(f"❌ 显示下载完成对话框时发生错误: {e}")
            # 降级到自定义毛玻璃对话框
            return question(
                self,
                "下载完成",
                f"铁粉圈图片下载完成！\n\n保存位置: {folder_path}\n\n是否打开文件夹？",
            )

    def eventFilter(self, obj, event):
        """事件过滤器 - 处理按钮点击事件"""
        try:
            if (
                obj == self.tiefenquan_browse_btn
                and event.type() == event.MouseButtonPress
            ):
                if event.button() == Qt.LeftButton:
                    print("🖱️ 通过事件过滤器检测到铁粉圈浏览按钮点击")
                    self.browse_tiefenquan_path()
                    return True
        except Exception as e:
            print(f"❌ 事件过滤器处理错误: {e}")

        return super().eventFilter(obj, event)

    # ====== 铁粉圈视频相关方法 ======

    def browse_tiefenquan_video_path(self):
        """浏览铁粉圈视频保存路径"""
        try:
            print("🔍 铁粉圈视频浏览按钮被点击")
            current_path = self.tiefenquan_video_path_input.text()
            print(f"📁 当前路径: {current_path}")

            folder = QFileDialog.getExistingDirectory(
                self, "选择铁粉圈视频保存路径", current_path if current_path else ""
            )

            if folder:
                print(f"✅ 选择的路径: {folder}")
                self.tiefenquan_video_path_input.setText(folder)
                # 添加日志提示
                self.add_tiefenquan_video_log(f"📁 已选择保存路径: {folder}")
            else:
                print("❌ 用户取消了路径选择")

        except Exception as e:
            print(f"❌ 浏览路径时发生错误: {e}")
            # 显示错误消息
            critical(self, "错误", f"浏览路径时发生错误:\n{str(e)}")

    def start_tiefenquan_video_download(self):
        """开始/停止铁粉圈视频下载"""
        print("🔥 铁粉圈视频下载按钮被点击!")
        try:
            if self.is_tiefenquan_video_downloading:
                # 停止下载
                print("⏹️ 停止下载")
                self.stop_tiefenquan_video_download()
            else:
                # 开始下载
                print("▶️ 开始下载")
                self.begin_tiefenquan_video_download()
        except Exception as e:
            print(f"❌ 下载按钮处理出错: {e}")
            import traceback

            traceback.print_exc()
            self.add_tiefenquan_video_log(f"❌ 按钮处理出错: {str(e)}")

    def begin_tiefenquan_video_download(self):
        """开始铁粉圈视频下载"""
        print("🚀 开始铁粉圈视频下载流程")

        try:
            url = self.tiefenquan_video_url_input.text().strip()
            print(f"📎 获取到URL: {url}")
            if not url:
                print("❌ URL为空")
                warning(self, "警告", "请输入铁粉圈视频链接！")
                return

            folder_path = self.tiefenquan_video_path_input.text().strip()
            print(f"📁 获取到保存路径: {folder_path}")
            if not folder_path:
                print("❌ 保存路径为空")
                warning(self, "警告", "请选择保存路径！")
                return

            # 验证URL格式
            if not url.startswith(("http://", "https://")):
                print("❌ URL格式无效")
                warning(self, "警告", "请输入有效的网页链接！")
                return

            # 验证是否是铁粉圈链接
            if "tiefenquan" not in url.lower():
                print("❌ 不是铁粉圈链接")
                warning(self, "警告", "请输入有效的铁粉圈链接！")
                return

            print("✅ URL和路径验证通过")
        except Exception as e:
            print(f"❌ 参数验证出错: {e}")
            import traceback

            traceback.print_exc()
            return

        try:
            # 设置下载状态
            print("🔄 设置下载状态")
            self.is_tiefenquan_video_downloading = True
            self.tiefenquan_video_download_btn.setText("停止下载")
            self.tiefenquan_video_download_btn.setStyleSheet(
                self.ui_styles.get_button_style("danger")
            )
            self.tiefenquan_video_progress_bar.setValue(0)

            # 清空日志
            print("📝 清空日志")
            self.tiefenquan_video_log_text.clear()

            # 添加开始日志
            print("📋 添加开始日志")
            self.add_tiefenquan_video_log("🚀 开始铁粉圈视频下载...")
            self.add_tiefenquan_video_log(f"📎 链接: {url}")
            self.add_tiefenquan_video_log(f"📁 保存路径: {folder_path}")

            # 确保保存目录存在
            print("📁 确保保存目录存在")
            if not os.path.exists(folder_path):
                os.makedirs(folder_path, exist_ok=True)
                print(f"✅ 创建目录: {folder_path}")

            # 创建并启动下载线程
            print("🧵 创建下载线程")
            self.tiefenquan_video_thread = TiefenquanVideoDownloadThread(
                self.tiefenquan_video_downloader, url, folder_path
            )
            print("▶️ 启动下载线程")
            self.tiefenquan_video_thread.start()
            print("✅ 下载线程已启动")

        except Exception as e:
            print(f"❌ 启动下载出错: {e}")
            import traceback

            traceback.print_exc()
            self.add_tiefenquan_video_log(f"❌ 启动下载出错: {str(e)}")
            # 重置状态
            self.is_tiefenquan_video_downloading = False
            self.tiefenquan_video_download_btn.setText("开始下载")
            self.tiefenquan_video_download_btn.setStyleSheet(
                self.ui_styles.get_button_style("primary")
            )

    def update_tiefenquan_video_progress(self, progress):
        """更新铁粉圈视频下载进度"""
        self.tiefenquan_video_progress_bar.setValue(progress)

    def update_tiefenquan_video_status(self, status):
        """更新铁粉圈视频下载状态"""
        self.add_tiefenquan_video_log(status)

    def tiefenquan_video_download_completed(self, success, filepath):
        """铁粉圈视频下载完成"""
        self.is_tiefenquan_video_downloading = False
        self.tiefenquan_video_download_btn.setText("开始下载")
        self.tiefenquan_video_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )

        if success:
            self.add_tiefenquan_video_log(f"✅ 视频下载完成！保存位置: {filepath}")
        else:
            self.add_tiefenquan_video_log("❌ 视频下载失败！")

    def show_tiefenquan_video_error(self, error_msg):
        """显示铁粉圈视频下载错误"""
        self.add_tiefenquan_video_log(f"❌ 错误: {error_msg}")
        self.is_tiefenquan_video_downloading = False
        self.tiefenquan_video_download_btn.setText("开始下载")
        self.tiefenquan_video_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )

    def stop_tiefenquan_video_download(self):
        """停止铁粉圈视频下载"""
        self.is_tiefenquan_video_downloading = False
        self.tiefenquan_video_download_btn.setText("开始下载")
        self.tiefenquan_video_download_btn.setStyleSheet(
            self.ui_styles.get_button_style("primary")
        )

        # 停止下载器
        if hasattr(self, "tiefenquan_video_downloader"):
            self.tiefenquan_video_downloader.stop_download()

        # 停止下载线程
        if hasattr(self, "tiefenquan_video_thread") and self.tiefenquan_video_thread:
            if self.tiefenquan_video_thread.isRunning():
                self.tiefenquan_video_thread.quit()
                self.tiefenquan_video_thread.wait(3000)  # 等待3秒

        self.add_tiefenquan_video_log("⏹️ 下载已停止")

    def clear_tiefenquan_video_log(self):
        """清空铁粉圈视频日志"""
        self.tiefenquan_video_log_text.clear()
        self.add_tiefenquan_video_log("📝 日志已清空")

    def add_tiefenquan_video_log(self, message):
        """添加铁粉圈视频日志"""
        from datetime import datetime

        timestamp = datetime.now().strftime("%H:%M:%S")
        log_message = f"[{timestamp}] {message}"
        self.tiefenquan_video_log_text.append(log_message)

        # 自动滚动到底部
        cursor = self.tiefenquan_video_log_text.textCursor()
        cursor.movePosition(cursor.End)
        self.tiefenquan_video_log_text.setTextCursor(cursor)


class DownloadCompleteDialog(QDialog):
    """铁粉圈下载完成的自定义毛玻璃对话框"""

    def __init__(self, parent=None, folder_path=""):
        super().__init__(parent)
        self.folder_path = folder_path
        self.setup_dialog()
        self.setup_ui()
        self.setup_animations()

    def setup_dialog(self):
        """设置对话框基本属性"""
        self.setWindowTitle("下载完成")
        self.setFixedSize(520, 340)
        self.setModal(True)
        self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

    def setup_ui(self):
        """设置UI界面"""
        # 主布局
        self.main_layout = QVBoxLayout()
        self.main_layout.setContentsMargins(40, 30, 40, 30)
        self.main_layout.setSpacing(25)

        # 应用毛玻璃效果
        self.apply_glassmorphism_effect()

        # 添加顶部间距
        self.main_layout.addSpacing(20)

        # 成功图标和标题
        icon_title_layout = QHBoxLayout()
        icon_title_layout.setSpacing(15)

        # 成功图标
        success_icon = QLabel("🎉")
        success_icon.setStyleSheet(
            """
            QLabel {
                color: #4CAF50;
                font-size: 32px;
                background: transparent;
                border: none;
            }
        """
        )
        icon_title_layout.addWidget(success_icon)

        # 标题
        title_label = QLabel("铁粉圈图片下载完成！")
        title_label.setStyleSheet(
            """
            QLabel {
                color: rgba(255, 255, 255, 0.95);
                font-size: 20px;
                font-weight: 600;
                font-family: 'Microsoft YaHei UI', sans-serif;
                background: transparent;
                border: none;
            }
        """
        )
        icon_title_layout.addWidget(title_label)
        icon_title_layout.addStretch()

        self.main_layout.addLayout(icon_title_layout)

        # 文件夹路径显示
        path_label = QLabel("保存位置:")
        path_label.setStyleSheet(
            """
            QLabel {
                color: rgba(255, 255, 255, 0.8);
                font-size: 14px;
                font-weight: 500;
                font-family: 'Microsoft YaHei UI', sans-serif;
                background: transparent;
                border: none;
                margin-bottom: 8px;
            }
        """
        )
        self.main_layout.addWidget(path_label)

        # 路径显示框
        self.path_display = QLabel(self.folder_path)
        self.path_display.setWordWrap(True)
        self.path_display.setStyleSheet(
            """
            QLabel {
                background: rgba(255, 255, 255, 0.15);
                border: 2px solid rgba(255, 255, 255, 0.3);
                border-radius: 12px;
                color: rgba(255, 255, 255, 0.9);
                font-size: 12px;
                font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
                padding: 12px 16px;
                max-height: 60px;
            }
        """
        )
        self.main_layout.addWidget(self.path_display)

        # 添加间距（减少间距，让按钮上移）
        self.main_layout.addSpacing(10)

        # 按钮容器
        button_container = QWidget()
        button_container.setStyleSheet(
            "QWidget { background: transparent; border: none; }"
        )
        button_layout = QHBoxLayout(button_container)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(20)

        button_layout.addStretch()

        # 取消按钮（不打开文件夹）
        self.cancel_button = QPushButton("稍后打开")
        self.cancel_button.setMinimumSize(140, 50)
        self.cancel_button.setStyleSheet(self.get_cancel_button_style())
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)

        # 确定按钮（打开文件夹）
        self.confirm_button = QPushButton("立即打开")
        self.confirm_button.setMinimumSize(140, 50)
        self.confirm_button.setStyleSheet(self.get_confirm_button_style())
        self.confirm_button.clicked.connect(self.accept)
        button_layout.addWidget(self.confirm_button)

        button_layout.addStretch()
        self.main_layout.addWidget(button_container)

        # 添加底部间距
        self.main_layout.addSpacing(20)

        # 设置默认焦点
        self.confirm_button.setFocus()

    def apply_glassmorphism_effect(self):
        """应用毛玻璃效果 - 粉色主题"""
        container = QWidget(self)
        container.setGeometry(0, 0, self.width(), self.height())

        # 设置容器的毛玻璃样式 - 粉色主题
        container.setStyleSheet(
            """
            QWidget {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 182, 193, 0.4),
                    stop:0.3 rgba(255, 192, 203, 0.35),
                    stop:0.7 rgba(255, 160, 180, 0.32),
                    stop:1 rgba(255, 175, 190, 0.38));
                border: 2px solid rgba(255, 182, 193, 0.5);
                border-radius: 25px;
            }
        """
        )

        # 将主布局设置到容器上
        if hasattr(self, "main_layout"):
            container.setLayout(self.main_layout)

    def get_cancel_button_style(self):
        """获取取消按钮样式"""
        return """
            QPushButton {
                background: rgba(255, 255, 255, 0.25);
                color: rgba(255, 255, 255, 0.9);
                border: 2px solid rgba(255, 255, 255, 0.4);
                border-radius: 18px;
                font-size: 15px;
                font-weight: 600;
                font-family: 'Microsoft YaHei UI', sans-serif;
            }
            QPushButton:hover {
                background: rgba(255, 255, 255, 0.3);
                color: rgba(255, 255, 255, 0.95);
                border: 2px solid rgba(255, 255, 255, 0.5);
            }
            QPushButton:pressed {
                background: rgba(255, 255, 255, 0.35);
                border: 2px solid rgba(255, 255, 255, 0.6);
            }
        """

    def get_confirm_button_style(self):
        """获取确定按钮样式"""
        return """
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 107, 129, 0.9),
                    stop:0.5 rgba(255, 142, 83, 0.9),
                    stop:1 rgba(255, 175, 123, 0.9));
                color: white;
                border: 2px solid rgba(255, 107, 129, 0.6);
                border-radius: 18px;
                font-size: 15px;
                font-weight: 700;
                font-family: 'Microsoft YaHei UI', sans-serif;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 107, 129, 1.0),
                    stop:0.5 rgba(255, 142, 83, 1.0),
                    stop:1 rgba(255, 175, 123, 1.0));
                border: 2px solid rgba(255, 107, 129, 0.8);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 87, 109, 1.0),
                    stop:0.5 rgba(255, 122, 63, 1.0),
                    stop:1 rgba(255, 155, 103, 1.0));
            }
        """

    def setup_animations(self):
        """设置动画效果"""
        # 淡入动画
        self.fade_animation = QPropertyAnimation(self, b"windowOpacity")
        self.fade_animation.setDuration(300)
        self.fade_animation.setEasingCurve(QEasingCurve.OutCubic)

        # 启动动画
        QTimer.singleShot(50, self.start_entrance_animation)

    def start_entrance_animation(self):
        """启动入场动画"""
        self.setWindowOpacity(0)
        self.fade_animation.setStartValue(0.0)
        self.fade_animation.setEndValue(1.0)
        self.fade_animation.start()

    def paintEvent(self, event):
        """自定义绘制事件 - 绘制背景"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制背景渐变 - 粉色系
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        gradient.setColorAt(0, QColor(255, 107, 129, 60))  # 粉红色
        gradient.setColorAt(0.25, QColor(255, 142, 83, 70))  # 橙粉色
        gradient.setColorAt(0.5, QColor(255, 175, 123, 80))  # 浅橙色
        gradient.setColorAt(0.75, QColor(255, 192, 203, 60))  # 浅粉色
        gradient.setColorAt(1, QColor(255, 182, 193, 70))  # 粉色

        painter.fillRect(self.rect(), QBrush(gradient))

        # 绘制装饰圆圈
        self.draw_decorative_circles(painter)

        super().paintEvent(event)

    def draw_decorative_circles(self, painter):
        """绘制装饰性圆圈 - 粉色系"""
        painter.setOpacity(0.08)

        # 圆圈1 - 粉红色系
        gradient1 = QRadialGradient(120, 100, 120)
        gradient1.setColorAt(0, QColor(255, 107, 129))
        gradient1.setColorAt(1, QColor(255, 182, 193))
        painter.setBrush(QBrush(gradient1))
        painter.setPen(Qt.NoPen)
        painter.drawEllipse(60, 40, 240, 240)

        # 圆圈2 - 橙粉色系
        gradient2 = QRadialGradient(450, 220, 140)
        gradient2.setColorAt(0, QColor(255, 142, 83))
        gradient2.setColorAt(1, QColor(255, 175, 123))
        painter.setBrush(QBrush(gradient2))
        painter.drawEllipse(350, 120, 280, 280)

        # 圆圈3 - 浅粉色系
        gradient3 = QRadialGradient(180, 320, 100)
        gradient3.setColorAt(0, QColor(255, 192, 203))
        gradient3.setColorAt(1, QColor(255, 175, 190))
        painter.setBrush(QBrush(gradient3))
        painter.drawEllipse(130, 270, 200, 200)

        painter.setOpacity(1.0)


class BatchDownloadThread(QThread):
    """批量下载线程"""

    progress_updated = Signal(int, int)
    status_updated = Signal(str)
    download_completed = Signal()
    error_occurred = Signal(str)

    def __init__(self, category, page, download_dir, settings, max_retries=3):
        super().__init__()
        self.category = category
        self.page = page
        self.download_dir = download_dir
        self.settings = settings
        self.max_retries = max_retries  # 最大重试次数
        self._stop_requested = False  # 添加停止标志

        # 创建复用的下载器实例，避免重复创建
        self.shared_downloader = None
        self._setup_shared_downloader()

    def request_stop(self):
        """请求停止下载"""
        self._stop_requested = True
        if self.shared_downloader:
            self.shared_downloader.stop_download()

    def _setup_shared_downloader(self):
        """设置共享下载器实例"""
        try:
            self.shared_downloader = WeimiquanDownloader()
            self.shared_downloader.set_settings(self.settings)
            # 连接信号到线程信号
            self.shared_downloader.status_updated.connect(self.status_updated.emit)
        except Exception as e:
            self.error_occurred.emit(f"初始化下载器失败: {str(e)}")

    def _cleanup_resources(self):
        """清理资源，防止内存泄漏"""
        try:
            if self.shared_downloader:
                # 断开信号连接
                try:
                    self.shared_downloader.status_updated.disconnect()
                except:
                    pass  # 忽略断开连接的错误

                # 停止下载器
                if hasattr(self.shared_downloader, "stop_download"):
                    self.shared_downloader.stop_download()

                # 调用下载器的资源清理方法
                if hasattr(self.shared_downloader, "cleanup_resources"):
                    self.shared_downloader.cleanup_resources()

                # 清空下载器引用
                self.shared_downloader = None

            # 强制垃圾回收
            import gc

            gc.collect()

            # 输出资源清理日志
            self.status_updated.emit("🧹 资源清理完成")

        except Exception as e:
            # 清理过程中的错误不应该影响主流程
            pass

    def _check_memory_usage(self):
        """检查内存使用情况"""
        try:
            if PSUTIL_AVAILABLE:
                # 获取当前进程的内存使用情况
                process = psutil.Process()
                memory_info = process.memory_info()
                memory_mb = memory_info.rss / 1024 / 1024  # 转换为MB

                # 获取系统内存使用率
                system_memory = psutil.virtual_memory()
                memory_percent = system_memory.percent

                return memory_mb, memory_percent
            else:
                # 如果psutil不可用，返回默认值
                return 0, 0
        except:
            return 0, 0

    def _force_memory_cleanup(self):
        """强制内存清理"""
        try:
            # 强制垃圾回收
            gc.collect()

            # 获取清理后的内存使用情况
            memory_mb, memory_percent = self._check_memory_usage()

            self.status_updated.emit(
                f"🧹 内存清理完成，当前使用: {memory_mb:.1f}MB ({memory_percent:.1f}%)"
            )

            return memory_mb, memory_percent
        except:
            return 0, 0

    def run(self):
        """运行批量下载"""
        try:
            self.status_updated.emit(
                f"开始爬取 {self.category} 分类，第 {self.page} 页"
            )

            # 爬取指定页面获取URL
            self.status_updated.emit(f"正在爬取第 {self.page} 页...")

            try:
                # 获取页面数据（静默模式）
                data = get_vmq_data(
                    self.page,
                    category_suffix=self.category,
                    use_proxy=True,
                    silent=True,
                )
                if data:
                    # 提取帖子信息（静默模式）
                    posts = extract_posts_from_response(data, silent=True)
                    all_urls = [post["url"] for post in posts if post.get("url")]
                    self.status_updated.emit(
                        f"第 {self.page} 页获取到 {len(all_urls)} 个链接"
                    )
                else:
                    self.error_occurred.emit(f"第 {self.page} 页获取失败")
                    return

            except Exception as e:
                self.error_occurred.emit(f"第 {self.page} 页爬取出错: {str(e)}")
                return

            if not all_urls:
                self.error_occurred.emit("未获取到任何下载链接")
                return

            self.status_updated.emit(
                f"爬取完成，共获取 {len(all_urls)} 个链接，开始下载..."
            )

            # 使用2个线程并发下载URL，图片下载仍使用多线程
            self._download_urls_concurrently(all_urls)
            self.download_completed.emit()

        except Exception as e:
            self.error_occurred.emit(f"批量下载过程中发生错误: {str(e)}")
        finally:
            # 确保资源被清理
            self._cleanup_resources()

    def _download_urls_concurrently(self, all_urls):
        """使用2个线程并发下载URL（每个URL内的图片仍使用多线程）"""
        max_workers = 2  # 减少并发数到2个，避免过多请求导致崩溃
        completed = 0
        successful = 0
        failed = 0

        self.status_updated.emit(
            f"🚀 开始并发下载 {len(all_urls)} 个URL，使用 {max_workers} 个线程，最大重试 {self.max_retries} 次"
        )
        self.status_updated.emit(f"📋 每个URL内的图片下载将使用多线程加速")

        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            # 提交所有下载任务，传递重试参数
            future_to_url = {
                executor.submit(self._download_single_url, url, i, self.max_retries): (
                    url,
                    i,
                )
                for i, url in enumerate(all_urls, 1)
            }

            self.status_updated.emit(
                f"📋 已提交 {len(future_to_url)} 个下载任务到线程池"
            )

            # 处理完成的任务
            for future in as_completed(future_to_url):
                if self._stop_requested or not self.isRunning():  # 检查是否被停止
                    self.status_updated.emit("⏹️ 检测到停止信号，终止批量下载")
                    # 取消所有未完成的任务
                    for f in future_to_url:
                        f.cancel()
                    break

                url, index = future_to_url[future]
                completed += 1

                try:
                    success, title, image_count = future.result()
                    if success:
                        successful += 1
                        # 详细的成功日志已经在 _download_single_url 中输出了
                    else:
                        failed += 1
                        # 详细的失败日志已经在 _download_single_url 中输出了
                except Exception as e:
                    failed += 1
                    self.status_updated.emit(
                        f"❌ ({completed}/{len(all_urls)}) 任务执行异常: {str(e)}"
                    )

                # 更新进度
                self.progress_updated.emit(completed, len(all_urls))

                # 显示总体进度
                self.status_updated.emit(
                    f"📊 进度: {completed}/{len(all_urls)} (成功: {successful}, 失败: {failed})"
                )

                # 每处理5个URL后检查内存使用情况
                if completed % 5 == 0:
                    memory_mb, memory_percent = self._check_memory_usage()

                    # 如果内存使用过高，强制清理
                    if (
                        memory_percent > 80 or memory_mb > 1000
                    ):  # 系统内存使用率>80% 或 进程内存>1GB
                        self.status_updated.emit(
                            f"⚠️ 内存使用过高 ({memory_mb:.1f}MB, {memory_percent:.1f}%)，执行清理..."
                        )
                        self._force_memory_cleanup()
                        time.sleep(1)  # 给系统一点时间

        # 显示最终统计
        self.status_updated.emit(
            f"🎉 批量下载完成！总计: {len(all_urls)}, 成功: {successful}, 失败: {failed}"
        )

    def _download_single_url(self, url, index, max_retries=3):
        """下载单个URL的内容（带重试功能）"""
        retry_count = 0
        last_error = None

        # 检查共享下载器是否可用
        if not self.shared_downloader:
            self.status_updated.emit(f"❌ ({index}) 下载器未初始化")
            return False, "下载器未初始化", 0

        while retry_count <= max_retries:
            # 检查是否被请求停止
            if self._stop_requested:
                self.status_updated.emit(f"⏹️ ({index}) 下载被停止")
                return False, "下载被停止", 0

            try:
                # 如果是重试，显示重试信息
                if retry_count > 0:
                    self.status_updated.emit(
                        f"🔄 ({index}) 第 {retry_count} 次重试: {url}"
                    )
                    # 重试前等待一段时间，避免频繁请求
                    time.sleep(2 * retry_count)  # 递增等待时间
                else:
                    self.status_updated.emit(f"🔍 ({index}) 正在处理: {url}")

                # 使用共享下载器实例，避免重复创建
                downloader = self.shared_downloader

                # 获取页面内容
                page_content = downloader.get_page_content(url)
                if not page_content:
                    raise Exception("无法访问页面")

                # 提取页面信息
                title, author = downloader.extract_page_info(page_content)

                # 清理标题，移除特殊字符
                title = re.sub(r'[<>:"/\\|?*]', "_", title)[:50]  # 限制长度

                # 搜索图片URL
                found_urls = downloader.search_cloudfront_images(page_content)

                if found_urls:
                    # 创建下载目录
                    folder_name = author if author != "未知作者" else title
                    folder_name = re.sub(r'[<>:"/\\|?*]', "_", folder_name)[
                        :50
                    ]  # 清理文件夹名
                    final_download_dir = os.path.join(self.download_dir, folder_name)

                    self.status_updated.emit(
                        f"📥 ({index}) 开始下载 {len(found_urls)} 张图片到: {folder_name}"
                    )

                    # 下载图片（静默下载，不显示每张图片的进度）
                    successful, failed = downloader.download_images_silent(
                        found_urls, final_download_dir
                    )

                    if successful > 0:
                        success_msg = (
                            f"✅ ({index}) {title} - 成功下载 {successful} 张图片"
                        )
                        if retry_count > 0:
                            success_msg += f" (重试 {retry_count} 次后成功)"
                        self.status_updated.emit(success_msg)
                    if failed > 0:
                        self.status_updated.emit(
                            f"⚠️ ({index}) {title} - {failed} 张图片下载失败"
                        )

                    return True, title, len(found_urls)
                else:
                    self.status_updated.emit(f"⚠️ ({index}) {title} - 未找到图片")
                    return True, title, 0

            except Exception as e:
                last_error = e
                retry_count += 1

                if retry_count <= max_retries:
                    self.status_updated.emit(
                        f"⚠️ ({index}) 处理失败: {str(e)} - 将进行第 {retry_count} 次重试"
                    )
                else:
                    error_msg = (
                        f"❌ ({index}) 处理失败 (已重试 {max_retries} 次): {str(e)}"
                    )
                    self.status_updated.emit(error_msg)
                    return False, f"错误: {str(e)}", 0

        # 如果所有重试都失败了
        error_msg = f"❌ ({index}) 所有重试都失败: {str(last_error)}"
        self.status_updated.emit(error_msg)
        return False, f"错误: {str(last_error)}", 0
